package com.template.templateuser.common.exception.handle;

import com.alibaba.fastjson.JSONObject;
import com.template.templatecommon.domain.Result;
import com.template.templatecommon.enums.HTTPEnum;
import com.template.templateuser.common.exception.exceptions.UserRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = UserRuntimeException.class)
    @ResponseBody
    public Result userExceptionHandler(HttpServletRequest req, UserRuntimeException e){
        logger.error("发生用户业务异常！原因是：{}",e.getCode());
        return Result.error(e.getCode(),e.getMessage());
    }
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常！原因是:",e);
        return Result.error(HTTPEnum.NULLPOINT_ERROR);
    }
    @Override
    public String toString() {
        return JSONObject.toJSONString(this);
    }
    /**
     * 处理请求方法不支持的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e){
        logger.error("发生请求方法不支持异常！原因是:",e);
        return Result.error(HTTPEnum.REQUEST_METHOD_SUPPORT_ERROR);
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        logger.error("未知异常！原因是:",e);
        return Result.error(HTTPEnum.INTERNAL_SERVER_ERROR);
    }

}
